// V-backend/src/app.js
const express = require('express');
const cors = require('cors');
const path = require('path');
require('dotenv').config();

const app = express();

// 中间件 - 修复CORS配置，添加管理后台端口
app.use(cors({
  origin: [
    'http://localhost:5173', // 粉丝端
    'http://localhost:5174', // 管理后台（备用端口）
    'http://localhost:5175'  // 管理后台
  ],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));

// API路由
app.use('/api/auth', require('./routes/auth'));
app.use('/api/activities', require('./routes/activities'));
app.use('/api/products', require('./routes/products'));
app.use('/api/cart', require('./routes/cart'));
app.use('/api/orders', require('./routes/orders'));
app.use('/api/admin', require('./routes/admin'));

// 新增管理后台路由
app.use('/api/admin', require('./routes/admin'));

// 测试路由
app.get('/api/test', (req, res) => {
  res.json({ 
    success: true, 
    message: '后端API服务正常运行!',
    timestamp: new Date().toISOString()
  });
});

// 健康检查
app.get('/health', (req, res) => {
  res.json({ status: 'OK', service: 'Virtual Community Backend' });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('全局错误:', err);
  res.status(500).json({
    success: false,
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: `路由 ${req.originalUrl} 不存在`
  });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`🚀 后端服务运行在: http://localhost:${PORT}`);
  console.log(`📊 健康检查: http://localhost:${PORT}/health`);
  console.log(`🧪 测试接口: http://localhost:${PORT}/api/test`);
  console.log(`🔐 认证接口: http://localhost:${PORT}/api/auth`);
  console.log(`🎯 活动接口: http://localhost:${PORT}/api/activities`);
  console.log(`🛍️ 商品接口: http://localhost:${PORT}/api/products`);
  console.log(`🛒 购物车接口: http://localhost:${PORT}/api/cart`);
  console.log(`📦 订单接口: http://localhost:${PORT}/api/orders`);
  console.log(`👨‍💼 管理后台接口: http://localhost:${PORT}/api/admin`); // 新增管理后台接口日志
});

module.exports = app;